import { request } from './request';

export async function addFormSubmitEvent(
    formElem: HTMLFormElement,
    successFn: () => void = () => {}
) {
    formElem.addEventListener("submit", (event) => {
        event.preventDefault();
        submitFormData(formElem, successFn);
    });
}

// TODO CSRF
export async function submitFormData(
    formElem: HTMLFormElement,
    successFn: () => void
) {
    const formData = new FormData(formElem);

    try {
        const response = await request(formElem.action, {
            method: "POST",
            body: formData,
            alertError: false,
        });
        const resp = await response.json();
        const success = resp['success'];
        if (success) {
            successFn();
        } else {
            formElem.outerHTML = resp['form_html'];
        }
    } catch (e) {
        console.error(e);
    }
}
